package video.simple100;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/***
 * 169. 多数元素
 */
public class LeetCode169 {


    @Test
    public void test() {
        int[] nums = {2, 2, 1, 1, 1, 2, 2};

        System.out.println(majorityElement(nums));
    }

    public int majorityElement(int[] nums) {
        // 1、定义计数器 (key=值  value=数量 )
        Map<Integer, Integer> counts = new HashMap<>();
        // 2、开始计数
        for (int i = 0; i < nums.length; i++) {
            if (counts.containsKey(nums[i])) {
                counts.put(nums[i], counts.get(nums[i]) + 1);
            } else {
                counts.put(nums[i], 1);
            }
        }
        // 3、获取计数器中最大的值进行返回
        int maxNum = 0;
        int maxVal = 0;
        for (Integer key : counts.keySet()) {
            Integer count = counts.get(key);
            if (count > maxNum) {
                maxNum = count;
                maxVal = key;
            }
        }
        return maxVal;
    }
}
